package com.validator.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.validator.dao.EquipmentTypeDao;
import com.validator.dao.OrderDao;
import com.validator.dao.PhonePrefixDao;
import com.validator.entity.EquipmentType;
import com.validator.entity.Order;
import com.validator.entity.PhonePrefix;
import com.validator.service.IOrderValidatorService;
import com.validator.util.Page;
import com.validator.util.Result;
import com.validator.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

@Service
public class OrderValidatorServiceImpl implements IOrderValidatorService {

    @Autowired
    private EquipmentTypeDao equipmentTypeDao;

    @Autowired
    private OrderDao orderDao;

    @Autowired
    private PhonePrefixDao phonePrefixDao;

    @Override
    public Result<Page<Order>> listByPage(
            String orderNumber,
            String equipmentType,
            String sn,
            String name,
            String email,
            String phoneNumber,
            String validateTime,
            Integer status,
            String orderBy,
            int page,
            int pageSize) {
        if (page <= 0) {
            page = 1;
        }
        if (pageSize <= 0) {
            pageSize = 20;
        }
        if (StringUtil.isBlank(orderNumber)) {
            orderNumber = null;
        }
        if (StringUtil.isBlank(equipmentType)) {
            equipmentType = null;
        }
        if (StringUtil.isBlank(sn)) {
            sn = null;
        }
        if (StringUtil.isBlank(name)) {
            name = null;
        }
        if (StringUtil.isBlank(email)) {
            email = null;
        }
        if (StringUtil.isBlank(phoneNumber)) {
            phoneNumber = null;
        }
        if (StringUtil.isBlank(validateTime)) {
            validateTime = null;
        }
        if (!"asc".equals(orderBy) && !"desc".equals(orderBy)) {
            orderBy = "asc";
        }
        if (status != null && status != -1 && status != 0 && status != 1) {
            status = null;
        }

        int start = (page - 1) * pageSize;
        int end = start + pageSize;

        List<Order> orders = orderDao.listByPage(
                orderNumber, equipmentType, sn, name, email, phoneNumber, validateTime, orderBy, status, start, end);
        long total = orderDao.countByPage(
                orderNumber, equipmentType, sn, name, email, phoneNumber, validateTime, orderBy, status);

        Page<Order> result = new Page<>();
        result.setPageSize(pageSize);
        result.setPage(page);
        result.setTotal(total);
        result.setData(orders);

        return Result.ok(result);
    }

    @Override
    public Result<Order> addOrder(String orderNumber) {
        if (StringUtil.isBlank(orderNumber)) {
            return Result.fail(502, "请填写订单号");
        }

        Order order = new Order();
        order.setOrderNumber(orderNumber);
        order.setStatus(0);

        orderDao.insert(order);
        return Result.ok(order);
    }

    @Transactional
    @Override
    public Result<List<Order>> addOrderByBatch(String[] orderNumbers) {
        if (orderNumbers == null || orderNumbers.length == 0) {
            return Result.ok(Collections.emptyList());
        }
        List<Order> orders = new ArrayList<>(orderNumbers.length);
        boolean hasErr = false;
        String errNumbers = "";
        for (String orderNumber : orderNumbers) {
            if (StringUtil.isBlank(orderNumber)) {
                continue;
            }
            try{
                Result<Order> addResult = addOrder(orderNumber);
                if(addResult.getCode() != 200){
                    hasErr = true;
                    errNumbers += orderNumber + ',';
                }
                orders.add(addResult.getData());
            } catch(Exception e){
                hasErr = true;
                errNumbers += orderNumber + ',';
            }
        }
        if(hasErr){
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return Result.fail(501, "以下订单号添加失败，请检查是否重复：" + errNumbers);
        }
        return Result.ok(orders);
    }

    @Override
    public Result<Order> validateByEquipmentTypeAndOrderNumber(String equipmentType, String orderNumber) {
        if (equipmentType == null || "".equals(equipmentType.trim())) {
            return Result.fail(500, "设备类型不能为空");
        }
        if (orderNumber == null || "".equals(orderNumber.trim())) {
            return Result.fail(501, "订单号不能为空");
        }
        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_number", orderNumber);
        Order order = orderDao.selectOne(orderQueryWrapper);

        if (order == null) {
            return Result.fail(502, "未找到订单");
        }

        order.setEquipmentType(equipmentType);
        orderDao.updateById(order);

        if (order.getStatus() == 1) {
            return Result.fail(503, "订单已验证");
        }
        if (order.getStatus() == -1) {
            return Result.fail(504, "订单已退货");
        }

        return Result.ok(order);
    }

    @Override
    public Result<Order> validOrder(Order order) {
        if (order == null) {
            return Result.fail(505, "未找到订单，提交失败");
        }
        String sn = order.getSn();
        String name = order.getName();
        String email = order.getEmail();
        String phoneNumber = order.getPhoneNumber();
        String equipmentType = order.getEquipmentType();
        if (StringUtil.isBlank(equipmentType)) {
            return fail(506, "设备类型不能为空");
        }
        if (StringUtil.isBlank(sn)) {
            return fail(506, "序列号不能为空");
        }
        if (StringUtil.isBlank(name)) {
            return fail(506, "姓名不能为空");
        }
        if (StringUtil.isBlank(email)) {
            return fail(506, "邮箱不能为空");
        }
        if (StringUtil.isBlank(phoneNumber)) {
            return fail(506, "手机号不能为空");
        }

        Order dbOrder = orderDao.selectById(order.getId());
        if (dbOrder == null) {
            return Result.fail(505, "未找到订单，提交失败");
        }

        dbOrder.setSn(sn);
        dbOrder.setName(name);
        dbOrder.setEmail(email);
        dbOrder.setPhoneNumber(phoneNumber);
        dbOrder.setValidateTime(new Date());
        dbOrder.setEquipmentType(equipmentType);
        dbOrder.setStatus(1);

        orderDao.updateById(dbOrder);

        return Result.ok(dbOrder);
    }

    @Override
    public Result<List<PhonePrefix>> listPhonePrefix() {
        return Result.ok(phonePrefixDao.selectList(null));
    }

    @Override
    public Result<EquipmentType> addEquipmentType(String type, int status) {
        if (StringUtil.isBlank(type)) {
            return Result.fail(500, "设备类型名称不能为空");
        }
        if (status != 0 && status != 1) {
            return Result.fail(501, "设备状态错误");
        }

        QueryWrapper<EquipmentType> equipmentTypeQueryWrapper = new QueryWrapper<>();
        equipmentTypeQueryWrapper.eq("`type`", type);
        Integer count = equipmentTypeDao.selectCount(equipmentTypeQueryWrapper);
        if (count > 0) {
            return Result.fail(502, "已存在的设备类型");
        }

        EquipmentType equipmentType = new EquipmentType();
        equipmentType.setType(type);
        equipmentType.setStatus(status);
        equipmentTypeDao.insert(equipmentType);
        return Result.ok(equipmentType);
    }

    @Override
    public Result<List<EquipmentType>> listEquipmentType() {
        QueryWrapper<EquipmentType> cond = new QueryWrapper<>();
        cond.orderByAsc("type");
        return Result.ok(equipmentTypeDao.selectList(cond));
    }

    @Override
    public Result<Boolean> deleteOrderByOrderNumber(String orderNumber) {
        if (StringUtil.isBlank(orderNumber)) {
            return Result.fail(500, "未找到订单");
        }

        QueryWrapper<Order> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("order_number", orderNumber);
        Order order = orderDao.selectOne(orderQueryWrapper);

        if (order == null || order.getId() <= 0) {
            return Result.fail(500, "未找到订单");
        }

        orderDao.deleteById(order.getId());

        return Result.ok(Boolean.TRUE);
    }

    @Override
    public Result<Boolean> deleteEquipmentTypeById(int id) {
        EquipmentType equipmentType = equipmentTypeDao.selectById(id);
        if (equipmentType == null || equipmentType.getId() <= 0) {
            return Result.fail(500, "未找到设备类型");
        }
        equipmentTypeDao.deleteById(equipmentType.getId());

        return Result.ok(Boolean.TRUE);
    }

    private Result fail(int code, String message) {
        return Result.fail(code, message);
    }
}
